﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WPFClient
{
    /// <summary>
    /// Interaction logic for Main.xaml
    /// </summary>
    public partial class Main : Page
    {
        //main page

        public ChatClient client; //class which communicates with server
        
        //pop up windows for changing password and adding friend
        ChangePass dialog;
        AddFriend addfriend;

        Chat chat; //window for chatting

        System.Timers.Timer dt; // timer to time updates
        public delegate void LogOutHandler();
        public event LogOutHandler LogOut;// instruction to log out
        public bool chatting; //becomes true while chat window is open
        public int chatID; //specifies id of chat to open when chat becomes true
        public Main(ChatClient _client)
        {
            InitializeComponent();
            client = _client; //loads client
            textBlock1.Text = client.account.getUsername(); //writes username of account logged in to at top of page
            StartRefreshing();
            
        }
        public void StartRefreshing()
        {
            if (dt != null) //if timer is already running
            {
                dt.Stop(); //stops timer
            }
            dt = new System.Timers.Timer(); //initializes timer
            dt.Interval = 2000;
            dt.Elapsed += new System.Timers.ElapsedEventHandler(RefreshBoxes);
            dt.Start(); //refreshBoxes method to be run every 2 seconds
        }
        private void RefreshBoxes(object sender, EventArgs e)
        {
            if (!chatting) //during normal operation
            {
                //updates boxes
                client.Read(); //gets 'go'
                client.GetAccount(); //updates client.account
                Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)delegate() //in main thread
                {
                    listBox1.ItemsSource = client.account.friendnames;
                    listBox2.ItemsSource = client.account.chatnames; //updates lists of friends and chats
                });
            }
            else //while chat window is open
            {
                chat currentChat = client.GetChat(chatID);

                String conversation = currentChat.GetConversation(); //gets conversation from server
                Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)delegate() //in main thread
                {
                    chat.textBlock1.Text = conversation; //displays it in text box
                });
            }
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //log out button
            dt.Stop(); //stops updating
            client.logout(); //runs log out method
            LogOut(); //triggers log out by MainWindow
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
             //change password button
             dt.Stop();
             dialog = new ChangePass();
             dialog.Show(); // creates new password change dialog box
             dialog.done+=new ChangePass.DoneHandler(dialog_done);
        }
        private void dialog_done()
        {           
            //every time button is pressed
             if (client.ChangePassword(dialog.getCurrent(), dialog.getNew())) //runs change password method - if successful
             {
                 Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)delegate() //in original thread
                 {
                     dialog.Close();
                     dt.Start(); // closes dialog and continues updating
                 });
             }
        }
        
        //new friend button and method - same as above
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            dt.Stop();
            addfriend = new AddFriend();
            addfriend.Show();
            addfriend.done += new AddFriend.DoneHandler(addfriend_done);
        }

       private void addfriend_done()
        {

            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                if (client.NewFriend(addfriend.getName()))
                {
                    addfriend.Close();
                    dt.Start();
                }
            });

        }


        private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // run on double click on friend name
            if (listBox1.SelectedIndex >= 0) //if selection was successfully made
            {
                if (!listBox2.Items.Contains((String)listBox1.SelectedValue + " , " + client.account.getUsername()) && !listBox2.Items.Contains(client.account.getUsername() + " , " + (String)listBox1.SelectedValue))
                //if no chat exists with only current account and friend
                {
                    IsEnabled = false; //disable window to avoid multiple simultaneous communications to server from same client
                    dt.Stop(); //stop updating
                    int friend = client.account.friendnames.IndexOf((String)listBox1.SelectedValue); //find friend index

                    client.NewChat(); //make new chat
                    client.AddMember(client.account.friends[friend]); //add friend to chat

                    chatID = client.account.chats.Count() - 1; //gets id of last chat on list (ie. chat just created)

                    chat = new Chat(client, chatID);
                    chat.Show(); //starts chat window
                    chatting = true;
                    dt.Start();

                    chat.Closed += new EventHandler(ChatClosed); //event for when window is closed
                    chat.button1.Click += new RoutedEventHandler(ChatButton_Click); //event for when button in chat window is clicked
                }
            }
        }
        private void ChatButton_Click(object sender, EventArgs e)
        {
            dt.Stop();
            client.say(chat.textBox1.Text); //sends message of what is in text box
            chat.textBox1.Text = "";
            dt.Start();
        }
        private void listBox2_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //run on click on chat
            IsEnabled = false;
            dt.Stop(); //stop updating to avoid simultaneous messages from same client


            chat selectedChat = client.GetChat(client.account.chats[listBox2.SelectedIndex]);

            chatID = selectedChat.GetID(); //gets id of selected chat
            client.StartChat(chatID); //starts chat
            
            chat = new Chat(client, chatID);
            chat.Show(); //start chat window
            chatting = true; //starts updating conversation rather than boxes

            chat.Closed+=new EventHandler(ChatClosed);// on window closed runs chat_Closed
            chat.button1.Click += new RoutedEventHandler(ChatButton_Click); //event for when button in chat window is clicked
            
            dt.Start(); //starts updating again
         }
        private void ChatClosed(object sender, EventArgs e)
        {
            IsEnabled = true;
            chatting = false;
        }
 
    }
}
